import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Text, Picker} from '@tarojs/components';
import {AtIcon} from 'taro-ui';
import {GetRequest} from "../../utils/tools";
import {http} from "../../utils/http";
import {newHttp} from "../../utils/request";
import {user} from '../../utils/user.service';
import {
	TARO_ENV,
	RESOURCE_URL,
	FETCH_WIFI_SUPPLIERS,
	FETCH_WIFI_LIST,
	FETCH_WIFI_CODE,
	FETCH_WIFI_DELETE
} from "../../constants/api";
import WiFiCode from "./codeShow";
import "./index.scss";

export default class WiFiMng extends Component {
    constructor(props) {
		super(props);
		this.state = {
			userId: null,
			page: 1,
			pageSize: 10,
			currentPage: 0,
			totalPages: 0,
			supplier_id: "",
			supplierChecked: "",
			supplierIndex: 0,
			supplierList: [],
			sellerId: "",
			wifiList: [],
			wifiCodeVisible: false,
			wifiCodeUrl: ""
		};
	}

  UNSAFE_componentWillMount() {}

    componentDidShow() {
		this.getSupplierList();
	}
    // get supplier list
    getSupplierList = async () => {
		const userData = await user.getUserData();
		const { userId } = userData;
		const userIdentity = await newHttp.catchGet(FETCH_WIFI_SUPPLIERS, {userId});
		this.setState({ userId });

		if (userIdentity) {
			let supplierChecked = '';
			let supplier_id = '';
			let supplierIndex = Taro.getStorageSync('supplierIndexRecordWiFi') || 0;

			if (userIdentity.supplierUserList.length > 0) {
				supplierChecked = userIdentity.supplierUserList[supplierIndex].company;
				supplier_id = userIdentity.supplierUserList[supplierIndex].supplier_id;
			}
			this.setState({
				supplierIndex,
				supplierChecked,
				supplier_id,
				supplierList: userIdentity.supplierUserList
			}, () => {
				this.getWiFiList();
			})
		}
	}
    // change supplier
    onChange(e) {
		const {supplierList} = this.state;
		const supplierIndex = Number(e.detail.value);
		const supplier_id = supplierList[supplierIndex].supplier_id;
		const supplierChecked = supplierList[supplierIndex].company;

		this.setState({supplier_id, supplierIndex, supplierChecked}, async () => {
			Taro.setStorageSync('supplierIndexRecordWiFi', supplierIndex);
			this.getWiFiList();
		})
	}
    // get wifi list
    getWiFiList = async () => {
		const { page, pageSize, currentPage, supplier_id } = this.state;
		Taro.showLoading({title: "加载中", mask: true});
		setTimeout(() => {
			Taro.hideLoading();
		}, 800)
		const res = await newHttp.catchGet(FETCH_WIFI_LIST, {supplier_id, page, size: pageSize}, true, "needPage");
		let lists = [], sellerId = "";
		if(res.data && Array.isArray(res.data) && res.data.length > 0) {
			// const { data, currentPage, totalPages } = res;
			lists = lists.concat(res.data);
			sellerId = res.sellerId;
		}
		this.setState({
			wifiList: lists,
			sellerId
		})
	};
    // edit
    handleEdit(item) {
		const { userId } = this.state;
		Taro.navigateTo({
            url: `/other/wifi/update?id=${item.id}&name=${item.name}&pwd=${item.pass}&ssid=${item.ssid}&userId=${userId}`
        })
	}
    // down
    handleDown = async (item) => {
		Taro.showLoading({ title: "获取中", mask: true });
		const { id } = item;
		const res = await newHttp.catchPost(FETCH_WIFI_CODE, {id});
		const { sellerId, wxVCodeImgStr } = res;

		if(res) {
			this.setState({
				wifiCodeVisible: true,
				wifiCodeUrl: wxVCodeImgStr
			}, () => {
				Taro.hideLoading();
			})
		}else {
			Taro.hideLoading();
		}
	}
    // delete
    handleDelete = (item) => {
		const _this = this;

		Taro.showModal({
			title: '提示',
			content: '确定删除吗？',
			success: async (res) => {
				if(res.confirm) {
					Taro.showLoading({ title: "获取中", mask: true });
					const { id } = item;
					const res = await newHttp.catchPost(FETCH_WIFI_DELETE, {id});
					res && _this.getWiFiList();
				}else if (res.cancel) {
					console.log('用户点击取消')
				}
			}
		})
	}
    // create
    wifiCreate = () => {
		const { userId } = this.state;
		Taro.navigateTo({
            url: `/other/wifi/update?userId=${userId}`
        })
	}
    // close code layer
    handleCloseLayer = () => {
		this.setState({ wifiCodeVisible: false, wifiCodeUrl: "" });
	}
    // testConnect
    testConnect(item) {
		const { sellerId } = this.state;
		Taro.navigateTo({
            url: `/other/wifi/connect?name=${item.name}|pass=${item.pass}|ssid=${item.ssid}|sellerId=${sellerId}`
        })
	}

    render() {
		const { supplierChecked, supplierIndex, supplierList, wifiList, wifiCodeVisible, wifiCodeUrl } = this.state;

		return (
			<View className="wifi-mng-page">
				<View className="item bg-clr hg ct top">
					<View className='header-bar'>
						<View className='head-picker'>
							{
								!!supplierList && supplierList.length > 0 &&
								<Picker value={supplierIndex} range={supplierList} rangeKey='company' onChange={this.onChange.bind(this)}>
									<View className={supplierChecked ? 'picker' : 'picker off'}>
										{supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
										<Text>切换</Text>
									</View>
								</Picker>
							}
						</View>
					</View>
				</View>
				<View className="item mid">
					<View className="wifi-list">
						{
							wifiList.length > 0 ?
							wifiList.map((item, index) => (
								<View className="wl-item" key={index}>
									<View className="wl-item_left" onClick={() => this.testConnect(item)}>{item.name}</View>
									<View className="wl-item_right">
										<AtIcon
											value="edit"
											size="17"
											color="#666"
											className="oper-icon"
											onClick={() => this.handleEdit(item)}
										/>
										<AtIcon
											value="download-cloud"
											size="18"
											color="#FEA000"
											className="oper-icon"
											onClick={() => this.handleDown(item)}
										/>
										<AtIcon
											value="trash"
											size="18"
											color="#f30"
											className="oper-icon"
											onClick={() => this.handleDelete(item)}
										/>
									</View>
								</View>
							))
							:
							<View className="empty-list">暂无WiFi</View>
						}
					</View>
				</View>
				<View className="item bg-clr hg ct bottom" onClick={this.wifiCreate}>创建WiFi</View>

				{
					wifiCodeVisible &&
					<WiFiCode visible={wifiCodeVisible} codeUrl={wifiCodeUrl} handleClose={this.handleCloseLayer} />
				}
			</View>
		)
	}
}
